package com.bb.blog.mybatis.handler;

import com.alibaba.fastjson.JSONObject;
import org.apache.ibatis.type.*;
import org.springframework.util.StringUtils;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collections;
import java.util.Map;

@MappedJdbcTypes(JdbcType.VARCHAR)
@MappedTypes({Map.class})
@Alias("VarcharToMap")
public class VarcharToMap extends BaseTypeHandler<Map> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Map parameter, JdbcType jdbcType) throws SQLException {
        String value = JSONObject.toJSONString(parameter);
        ps.setString(i, value);
    }

    @Override
    public Map getNullableResult(ResultSet rs, String columnName) throws SQLException {

        String value = rs.getString(columnName);
        if (StringUtils.isEmpty(value)) {
            return Collections.emptyMap();
        }
        return JSONObject.parseObject(value, Map.class);
    }

    @Override
    public Map getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String value = rs.getString(columnIndex);
        if (StringUtils.isEmpty(value)) {
            return Collections.emptyMap();
        }

        return JSONObject.parseObject(value, Map.class);
    }

    @Override
    public Map getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String value = cs.getString(columnIndex);
        if (StringUtils.isEmpty(value)) {
            return Collections.emptyMap();
        }
        return JSONObject.parseObject(value, Map.class);
    }
}
